package high.concurent.util;

import com.google.code.kaptcha.Producer;
import high.concurrent.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 各种验证码工具类
 *
 * @Description
 * @Author 黄保泽
 * @Version 1.0
 **/
@Slf4j
@Component
public class CaptchaUtil {


    /**
     * 获取图形验证码
     * @param response
     * @return 返回验证码
     */
    public static String  getCaptcha(Producer captchaProducer, HttpServletResponse response){

        // 生成验证码
        String captchaText = captchaProducer.createText();
        log.info("图形验证码:{}",captchaText);

        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            // TODO 这个是转成流，返给前端， 把注释掉的内容解开，然后把 ServletOutputStream outputStream = null; 注释掉即可。
            // TODO 返回的流可以和验证码【拼接到一起】 或者 【返回数组】，然后到impl中分割，再保存到redis
//            ByteArrayOutputStream outputStream =new ByteArrayOutputStream();
            ImageIO.write(bufferedImage,"jpg",outputStream);
//            String base64Code = Base64.encodeBase64String(outputStream.toByteArray());
//            log.info(base64Code);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            log.error("获取图形验证码异常:{}",e);
        }

        return captchaText;
    }



    /**
     * 获取缓存的key
     * @param request
     * @return
     */
    public static String getCaptchaKey(HttpServletRequest request){

        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");

        String key = "user-service:captcha:"+ CommonUtil.MD5(ip+userAgent);

        log.info("ip={}",ip);
        log.info("userAgent={}",userAgent);
        log.info("key={}",key);

        return key;

    }

}
